import fs from "fs";
import common from "../../lib/common/common.js"


const isAvatar = 5 // 设置前几名有头像
const isRankingsNumber = 75 // 排行榜显示数量

fs.mkdirSync('data/发言记录', { recursive: true });
export class example extends plugin {
    constructor() {
        super({
            name: '发言榜',
            dsc: 'example',
            event: 'message',
            priority: 1,
            rule: [
                {
                    reg: '^#发言榜$',
                    fnc: 'GetRanking'
                },
                {
                    reg: '^#昨日发言榜$',
                    fnc: 'GetYesterdayRanking'
                },
                {
                    reg: /.*/,
                    fnc: 'RecordAndEnterMessage',
                    log: false
                }
            ]
        });
    }

    async GetRanking(e) {
        const DATA_FILE = 'data/Ranking of speakers.json';
        if (!e.isGroup) {
            return false;
        }
        const msgArr = [];
        const GROUP_ID = e.group_id;
        let DATA_DATA = {};

        try {
            DATA_DATA = JSON.parse(fs.readFileSync(DATA_FILE, 'utf8'));
        } catch (error) {
            return e.reply("读取数据文件出错：\n", error);
        }

        const groupData = DATA_DATA[GROUP_ID];
        if (!groupData) {
            return e.reply("没有这个群的排名数据。");
        }

        const ranking = Object.entries(groupData)
            .map(([userId, userData]) => ({
                userId,
                nickname: userData.nickname,
                count: userData.count
            }))
            .sort((a, b) => b.count - a.count)
            .slice(0, isRankingsNumber);

        ranking.forEach((entry, index) => {
            let msg = [];
            if (index < isAvatar) {
                msg.push(segment.image(`https://q1.qlogo.cn/g?b=qq&nk=${entry.userId}&s=160`));
            }
            msg.push(
                `Top${index + 1}：${entry.nickname} \n`,
                `QQ：${entry.userId}\n`,
                `发送消息数：${entry.count}条`
            );
            msgArr.push(msg);
        });
        return e.reply(await common.makeForwardMsg(e, msgArr, `群[${GROUP_ID}]发言排行\n机器人在线的情况下记录`));
    }


    async GetYesterdayRanking(e) {
        if (!e.isGroup) {
            return false;
        }
        const msgArr = [];
        const GROUP_ID = e.group_id;
        const yesterdayDate = getYesterdayDate();
        const DATA_FILE = `data/发言记录/${yesterdayDate}.json`;

        if (!fs.existsSync(DATA_FILE)) {
            return e.reply("昨日没有记录。");
        }

        let DATA_DATA = {};

        try {
            DATA_DATA = JSON.parse(fs.readFileSync(DATA_FILE, 'utf8'));
        } catch (error) {
            return e.reply("读取数据文件出错：\n", error);
        }

        const groupData = DATA_DATA[GROUP_ID];
        if (!groupData) {
            return e.reply("没有这个群的排名数据。");
        }

        const yesterdayData = groupData.yesterday;
        if (!yesterdayData) {
            return e.reply("昨日没有记录。");
        }

        const ranking = Object.entries(yesterdayData)
            .map(([userId, userData]) => ({
                userId,
                nickname: userData.nickname,
                count: userData.count
            }))
            .sort((a, b) => b.count - a.count)
            .slice(0, isRankingsNumber);

        ranking.forEach((entry, index) => {
            const msg = [
                `Top${index + 1}：${entry.nickname} \n`,
                `QQ：${entry.userId}\n`,
                `发送消息数：${entry.count}条`
            ];
            msgArr.push(msg);
        });

        return e.reply(await common.makeForwardMsg(e, msgArr, `群[${GROUP_ID}]昨日发言排行\n机器人在线的情况下记录`));
    }

    async RecordAndEnterMessage(e) {
        if (!e.isGroup) {
            return false;
        }

        const GROUP_ID = e.group_id;
        const USER_ID = e.user_id;
        const USER_NICKNAME = e.nickname;
        const yesterdayDate = getCurrentDate();
        const DATA_FILE_RECORD = `data/发言记录/${yesterdayDate}.json`;
        const DATA_FILE_RANKING = 'data/Ranking of speakers.json';

        let DATA_DATA_RECORD = {};
        let DATA_DATA_RANKING = {};

        try {
            if (fs.existsSync(DATA_FILE_RECORD)) {
                DATA_DATA_RECORD = JSON.parse(fs.readFileSync(DATA_FILE_RECORD, 'utf8'));
            }
            DATA_DATA_RANKING = JSON.parse(fs.readFileSync(DATA_FILE_RANKING, 'utf8'));
        } catch (error) {
            console.error("Error reading data file:", error);
            return;
        }

        DATA_DATA_RECORD[GROUP_ID] = DATA_DATA_RECORD[GROUP_ID] || {};
        DATA_DATA_RECORD[GROUP_ID].yesterday = DATA_DATA_RECORD[GROUP_ID].yesterday || {};
        DATA_DATA_RECORD[GROUP_ID].yesterday[USER_ID] = DATA_DATA_RECORD[GROUP_ID].yesterday[USER_ID] || {
            count: 0,
            nickname: USER_NICKNAME
        };
        DATA_DATA_RECORD[GROUP_ID].yesterday[USER_ID].count += 1;

        DATA_DATA_RANKING[GROUP_ID] = DATA_DATA_RANKING[GROUP_ID] || {};
        DATA_DATA_RANKING[GROUP_ID][USER_ID] = DATA_DATA_RANKING[GROUP_ID][USER_ID] || {
            count: 0,
            nickname: USER_NICKNAME
        };
        DATA_DATA_RANKING[GROUP_ID][USER_ID].count += 1;
        DATA_DATA_RANKING[GROUP_ID][USER_ID].nickname = USER_NICKNAME;

        try {
            fs.writeFileSync(DATA_FILE_RECORD, JSON.stringify(DATA_DATA_RECORD, null, 4), 'utf8');
            fs.writeFileSync(DATA_FILE_RANKING, JSON.stringify(DATA_DATA_RANKING, null, 4), 'utf8');
        } catch (error) {
            console.error("Error writing data file:", error);
        }

        return false;
    }

}

function getYesterdayDate() {
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    const year = yesterday.getFullYear();
    const month = String(yesterday.getMonth() + 1).padStart(2, '0');
    const day = String(yesterday.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

function getCurrentDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}